package com.kolon.business.mCafeteriaMenu.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.Document;
import org.jdom.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.framework.constant.Constant;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.DateUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mCafeteriaMenu.controller.MCafeteriaMenuController")
public class MCafeteriaMenuController implements SimpleController {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/business/mCafeteriaMenu/mCafeteriaMenu.do")
	public ModelAndView controller(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 도메인
		String url = MsgUtil.getMessage("xml.url");
		// 세션
		HttpSession httpSession = request.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_USER_INFO);
		String id = (String)userMap.get("userId");
		String pw = (String)userMap.get("userPw");
		// 기본식당 쿠키 추출
		Cookie[] cookies = request.getCookies();
		String resCookie = "";
		for(int i=0 ; i<cookies.length ; i++) {
			Cookie cookie = cookies[i];
			if(cookie.getName().equals("resCookieVal")) {
				resCookie = cookie.getValue();
				break;
			}
		}
		// 캘린더 관련 다음/이전/현재일 계산
		String YMD = ComUtil.getNullCheck(request.getParameter("YMD"), DateUtil.getToday());
		String year = ComUtil.getNullCheck(YMD.substring(0, 4), DateUtil.getYearStr());
		String month = ComUtil.getNullCheck(YMD.substring(5, 7), DateUtil.getMonthStr());
		String day = ComUtil.getNullCheck(YMD.substring(8, 10), DateUtil.getDayStr());
		// 형 변환
		int prevYear = ComUtil.sToi(year);
		int prevMonth = ComUtil.sToi(month);
		int prevDay = ComUtil.sToi(day)-1;
		int nextYear = ComUtil.sToi(year);
		int nextMonth = ComUtil.sToi(month);
		int nextDay = ComUtil.sToi(day)+1;
		// 이전 년월일
		if (prevDay < 1 ) {
			prevMonth = prevMonth - 1;
			prevDay = DateUtil.getLastDay(year, ComUtil.iTos(ComUtil.sToi(month)-1));
			if (prevMonth < 1 ) {
				prevYear = prevYear - 1;
				prevMonth = 12;
			}
		}
		// 다음 년월일
		if (nextDay > DateUtil.getLastDay(year, month)) {
			nextMonth = nextMonth + 1;
			nextDay = 1;
			if (nextMonth > 12 ) {
				nextYear = nextYear + 1;
				nextMonth = 1;
			}
		}
		String CafeCD = "1";
		if(!"".equals(request.getParameter("res") == null ? "" : request.getParameter("res"))) {
			CafeCD = request.getParameter("res"); 
		}else if(!"".equals(resCookie)&& "".equals(request.getParameter("res") == null ? "" : request.getParameter("res"))) {
			CafeCD = resCookie;
		}else if("".equals(resCookie) && "".equals(request.getParameter("res") == null ? "" : request.getParameter("res"))) {
			CafeCD = "1";
		}
		// URL 생성
		StringBuffer buffer = new StringBuffer();
		buffer.append(url);
		buffer.append("/cafeteria_menu.aspx?Gubun=").append("YMDCafeMenu");
		buffer.append("&CafeCD=").append(CafeCD);
		buffer.append("&YMD=").append(YMD);
		buffer.append("&userid=").append(id);
		buffer.append("&pw=").append(pw);
		// XML DOCUMENT 및 인증 처리
		Document doc = ComUtil.getDocument(buffer.toString(), id, pw);
		Element element = doc.getRootElement();
		List xmlList = element.getChildren();
		Iterator itXml = xmlList.iterator();
		Map map = null;
		// XML 데이터 
		if (itXml.hasNext()) {
			Element el = (Element)itXml.next();
			map = new HashMap();
			map.put("CafeCD", el.getChild("CafeCD").getText());
			map.put("YMD", el.getChild("YMD").getText());
			map.put("Morning", el.getChild("Morning").getText().replaceAll("<br>", ", "));
			map.put("Lunch1", el.getChild("Lunch1").getText().replaceAll("<br>", ", "));
			map.put("Lunch2", el.getChild("Lunch2").getText().replaceAll("<br>", ", "));
			map.put("Dinner", el.getChild("Dinner").getText().replaceAll("<br>", ", "));
			map.put("UserID", el.getChild("UserID").getText());
			map.put("UserName", el.getChild("UserName").getText());
			map.put("CreateDate", el.getChild("CreateDate").getText());
			map.put("RatingScore", el.getChild("RatingScore").getText());
			map.put("RatingCnt", el.getChild("RatingCnt").getText());
			map.put("Rating", el.getChild("Rating").getText());
		}
		// 식당정보
		StringBuffer buffer2 = new StringBuffer();
		buffer2.append(url);
		buffer2.append("/cafeteria_menu.aspx?Gubun=").append("CafeteriaName");
		buffer2.append("&userid=").append(id);
		buffer2.append("&pw=").append(pw);
		// XML DOCUMENT 및 인증 처리
		Document doc2 = ComUtil.getDocument(buffer2.toString(), id, pw);
		Element element2 = doc2.getRootElement();
		List xmlList2 = element2.getChildren();
		Iterator itXml2 = xmlList2.iterator();
		Map map2 = null;
		List mapList = new ArrayList(); 
		// XML 데이터 
		while (itXml2.hasNext()) {
			Element el2 = (Element)itXml2.next();
			map2 = new HashMap();
			map2.put("CafeCD", el2.getChild("CafeCD").getText());
			map2.put("CafeName", el2.getChild("CafeName").getText());
			mapList.add(map2);
		}
		// 리턴
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("map", map);
		modelAndView.addObject("mapList", mapList);
		modelAndView.addObject("prevYear", ComUtil.toZeroStr(prevYear, 4));
		modelAndView.addObject("prevMonth", ComUtil.toZeroStr(prevMonth, 2));
		modelAndView.addObject("prevDay", ComUtil.toZeroStr(prevDay, 2));
		modelAndView.addObject("year", year);
		modelAndView.addObject("month", month);
		modelAndView.addObject("day", day);
		modelAndView.addObject("nextYear", ComUtil.toZeroStr(nextYear, 4));
		modelAndView.addObject("nextMonth", ComUtil.toZeroStr(nextMonth, 2));
		modelAndView.addObject("nextDay", ComUtil.toZeroStr(nextDay, 2));
		modelAndView.addObject("resCookie", resCookie);		
		modelAndView.addObject("res", request.getParameter("res") == null ? "1" : request.getParameter("res"));
		return modelAndView;
	}

}
